package com.guigu.servicegoods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.common_util.pojo.config.CacheKey;
import com.guigu.common_util.pojo.utils.Result;
import com.guigu.servicegoods.domain.TbBrand;
import com.guigu.servicegoods.domain.TbCategory;
import com.guigu.servicegoods.mapper.TbBrandMapper;
import com.guigu.servicegoods.service.TbBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.servicegoods.service.TbCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 品牌表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
@EnableScheduling
public class TbBrandServiceImpl extends ServiceImpl<TbBrandMapper, TbBrand> implements TbBrandService {

    @Autowired
    private TbBrandMapper brandMapper;

    @Autowired
    private TbCategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result findPage(Map<String, Object> searchMap, Integer page, Integer size) {
        QueryWrapper<TbBrand> wrapper = createExample(searchMap);
        //创建page对象
        Page<TbBrand> pageBrand = new Page<>(page,size);
        baseMapper.selectPage(pageBrand,wrapper);
        return Result.ok().data("row",pageBrand.getRecords()).data("total",pageBrand.getTotal());
    }

    @Scheduled(fixedRate = 86400000)
//    @Scheduled(cron = "0 0 2 * * ?")
    @Override
    public void findListByCategoryName() {
        List<TbCategory> categoryList = categoryService.list(null);
        for (TbCategory category:categoryList) {
            List<Map> brandList = brandMapper.findListByCategoryName(category.getName());
            redisTemplate.boundHashOps(CacheKey.CATEGORY_BRAND).put(category.getName(),brandList);
        }
        System.out.println("执行了定时方法brand");
    }

    // 根据查询条件封装模块对象
    private QueryWrapper<TbBrand> createExample(Map<String, Object> searchMap) {
        QueryWrapper<TbBrand> wrapper = new QueryWrapper<>();
        if(searchMap!=null) {
            if(searchMap.get("id")!=null)
                wrapper.eq("id",searchMap.get("id"));
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name")))
                wrapper.like("name",searchMap.get("name"));
        }
        return wrapper;
    }
}
